import Taro from "@tarojs/taro";
import { getTestGetverificationcode } from "@/apis/endpoint/test";
import { useCutdown } from "@/hooks/useCutdown";
import { useState } from "react";

interface Action {
  (mobile: string): Promise<unknown>
}
export function useVerifyCode(duration: number, action: Action) {
  const [lock, setLock] = useState(false)
  const { remain, running, start, stop } = useCutdown(duration)
  async function triggerSend(mobile: string) {
    if (lock || running) return;
    if (!mobile) {
      Taro.showToast({
        title: "请先输入手机号",
        icon: "none"
      })
      return
    }
    try {
      setLock(true)
      await action(mobile)
      setLock(false)
      if (process.env.NODE_ENV === "development") {
        const { code } = await getTestGetverificationcode({ mobile }).send()
        Taro.setClipboardData({
          data: code
        })
      } else {
        Taro.showToast({
          title: "验证码发送成功",
          icon: "success"
        })
      }
      start()
    } catch (error) {
      console.log("useVerifyCode", error)
      setLock(false)
      Taro.showToast({
        title: "验证码发送失败",
        icon: "error"
      })
      stop()
    }
  }
  function reset() {
    setLock(false)
    stop()
  }
  return {
    remain,
    running,
    triggerSend,
    reset
  }
}
